package com.retain.system.controller;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

/**
 * @author: LiuWei
 * @date: Create in 10:34 2018/10/16
 */
@RestController
public class AuthController {

    @GetMapping("/login")
    public String login(@RequestParam final String account, @RequestParam final String password) {
        JSONObject jsonObject = new JSONObject();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(account, password);
        try {
            subject.login(token);
            jsonObject.put("token", subject.getSession().getId());
            jsonObject.put("msg", "登录成功");
        } catch (IncorrectCredentialsException e) {
            jsonObject.put("msg", "密码错误");
        } catch (LockedAccountException e) {
            jsonObject.put("msg", "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            jsonObject.put("msg", "该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toJSONString();
    }

    @RequestMapping(value = "/logout")
    public String logout() {
        SecurityUtils.getSubject().logout();
        return "logout";
    }

    //    @RequiresPermissions(value = { "admin:seconde", "user:create" }, logical = Logical.OR)
    @RequestMapping(value = "/guest", method = RequestMethod.GET)
    public String test() {
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.hasRole("admin"));
        System.out.println(subject.hasRole("root"));
        System.out.println(subject.hasRole("111"));
        System.out.println(subject.isPermitted("seconde"));
        System.out.println(subject.isPermitted("/seconde"));
        return "111111111";
    }
}
